﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using NewTech_BookStore.Properties;
using System.Text.RegularExpressions;

namespace NewTech_BookStore
{
    public partial class MainForm : Form
    {
        private List<Bill> _lstBill = new List<Bill>();
        private List<Book> _lstBook = new List<Book>();
        private Payment _payment = new Payment();

        //-------------------

        public MainForm()
        {
            InitializeComponent();
            MinimumSize = new Size(326, 550);
            Size = new Size(326, 550);
        }

        public override sealed Size MinimumSize
        {
            get { return base.MinimumSize; }
            set { base.MinimumSize = value; }
        }

        private void MainLoad(object sender, EventArgs e)
        {
            chbxT1ChoseBookID.Checked = true;
            btnT1SelectBook.Enabled = false;
            chbxT2ChoseUserName.Checked = true;
            btnT2Select.Enabled = false;
            chbxT3Select.Checked = true;
            grbxT3Bill.Enabled = false;
            grbxT3ListBook.Enabled = false;
            btnT3NewPayment.Enabled = false;
            btnT3FinalPayment.Enabled = false;
            radT4Title.Checked = true;
            bookTableAdapter.Fill(newTech_BookStoreDataSet.Book);
            usersTableAdapter.Fill(newTech_BookStoreDataSet.Users);
        }

        private void MainTabSelected(object sender, TabControlEventArgs e)
        {
            var s1 = new Size(326, 568);
            var s2 = new Size(604, 568);
            switch (mainTab.SelectedTab.Text)
            {
                case "Book":
                    MinimumSize = s1;
                    Size = s1;
                    break;
                case "Customer":
                    MinimumSize = s1;
                    Size = s1;
                    break;
                case "Bill":
                    MinimumSize = s2;
                    txtT3PurchaseDay.Text = DateTime.Today.ToString("dd/MM/yyyy");
                    break;
                case "Search Book":
                    MinimumSize = s1;
                    Size = s1;
                    break;
                case "":
                    MinimumSize = s2;
                    break;
            }
        }

        //--------------tab 1

        private void ChbxT1ChoseBookIdCheckedChanged(object sender, EventArgs e)
        {
            if (chbxT1ChoseBookID.Checked)
            {
                txtT1BookID.Enabled = false;
                cbxT1BookID.Enabled = true;
                btnT1SelectBook.Enabled = false;
                btnT1Insert.Enabled = false;
            }
            else
            {
                btnT1Insert.Enabled = true;
                txtT1BookID.Enabled = true;
                cbxT1BookID.Enabled = false;
                btnT1SelectBook.Enabled = true;
            }
        }

        private void BtnT1SelectBookClick(object sender, EventArgs e)
        {
            string bookid = txtT1BookID.Text;
            cbxT1BookID.SelectedValue = bookid;
            if(cbxT1BookID.Text=="")
            {
                txtT1Author.Text = "";
                txtT1BookID.Text = "";
                txtT1Category.Text = "";
                txtT1Description.Text = "";
                txtT1ISBN.Text = "";
                txtT1Price.Text = "";
                txtT1Publisher.Text = "";
                txtT1Title.Text = "";
            }
        }

        private void BtnT1InsertClick(object sender, EventArgs e)
        {
            try
            {
                int x = bookTableAdapter.InsertBook(
                    txtT1BookID.Text,
                    txtT1Title.Text,
                    txtT1Category.Text,
                    txtT1Author.Text,
                    txtT1Publisher.Text,
                    txtT1ISBN.Text,
                    Convert.ToDecimal(txtT1Price.Text),
                    txtT1Description.Text);
                if (x == 1)
                    lbStatus.Text = @"Insert Successful";

                bookTableAdapter.Fill(newTech_BookStoreDataSet.Book);
            }
            catch (Exception ex)
            {
                lbStatus.Text = @"Error";
                MessageBox.Show("Thong tin khong hop le vui long kiem tra lai\n\n" + ex.Message);
            }
        }

        private void BtnT1UpdateClick(object sender, EventArgs e)
        {
            string bookid = cbxT1BookID.Enabled ? cbxT1BookID.Text : txtT1BookID.Text;
            try
            {
                int x = bookTableAdapter.UpdateBook(txtT1Title.Text, txtT1Category.Text, txtT1Author.Text,
                                                    txtT1Publisher.Text, Convert.ToDecimal(txtT1Price.Text),
                                                    txtT1Description.Text, bookid);
                if (x == 1)
                    lbStatus.Text = @"Update Successful";
            }
            catch (Exception ex)
            {
                lbStatus.Text = @"Error";
                MessageBox.Show(ex.Message);
            }
        }

        private void BtnT1DeleteClick(object sender, EventArgs e)
        {
            string bookid = cbxT1BookID.Enabled ? cbxT1BookID.Text : txtT1BookID.Text;
            try
            {
                int x = bookTableAdapter.DeleteBook(bookid);
                if (x == 1)
                {
                    lbStatus.Text = @"Delete Successful";
                    bookTableAdapter.Fill(newTech_BookStoreDataSet.Book);
                }
            }
            catch (Exception ex)
            {
                lbStatus.Text = @"Error";
                MessageBox.Show(ex.Message);
            }
        }

        //--------------tab 2

        private void ChbxT2ChoseUserNameCheckedChanged(object sender, EventArgs e)
        {
            if (chbxT2ChoseUserName.Checked)
            {
                txtT2UserName.Enabled = false;
                btnT2Select.Enabled = false;
                cbxT2UserName.Enabled = true;
                btnT2Insert.Enabled = false;
            }
            else
            {
                txtT2UserName.Enabled = true;
                btnT2Select.Enabled = true;
                cbxT2UserName.Enabled = false;
                btnT2Insert.Enabled = true;
            }
        }

        private void BtnT2SelectClick(object sender, EventArgs e)
        {
            string usename = txtT2UserName.Text;
            cbxT2UserName.SelectedValue = usename;
            if(cbxT2UserName.Text=="")
            {
                txtT2Address.Text = "";
                txtT2City.Text = "";
                txtT2Email.Text = "";
                txtT2FirstName.Text = "";
                txtT2LastName.Text = "";
                txtT2PassWord.Text = "";
                txtT2Phone.Text = "";
                txtT2State.Text = "";
                txtT2UserName.Text = "";
            }
        }

        //private void BtnT2InsertClick(object sender, EventArgs e)
        //{
        //    try
        //    {
        //        int x = usersTableAdapter.InsertUser(txtT2UserName.Text,
        //                                             txtT2PassWord.Text,
        //                                             txtT2FirstName.Text,
        //                                             txtT2LastName.Text,
        //                                             txtT2Address.Text,
        //                                             txtT2State.Text,
        //                                             txtT2City.Text,
        //                                             txtT2Phone.Text,
        //                                             txtT2Email.Text
        //            );
        //        if (x == 1)
        //            lbStatus.Text = @"Insert Successful";
        //        usersTableAdapter.Fill(newTech_BookStoreDataSet.Users);
        //    }
        //    catch (Exception ex)
        //    {
        //        lbStatus.Text = @"Error";
        //        MessageBox.Show(ex.Message);
        //    }
        //}


        private void BtnT2InsertClick(object sender, EventArgs e)
        {
            // if (chkCusInfo())
            // {
            try
            {
                int x = usersTableAdapter.InsertUser(txtT2UserName.Text,
                                                     txtT2PassWord.Text,
                                                     txtT2FirstName.Text,
                                                     txtT2LastName.Text,
                                                     txtT2Address.Text,
                                                     txtT2State.Text,
                                                     txtT2City.Text,
                                                     txtT2Phone.Text,
                                                     txtT2Email.Text
                    );
                if (x == 1)
                    lbStatus.Text = @"Insert Successful";
                usersTableAdapter.Fill(newTech_BookStoreDataSet.Users);
            }
            catch (Exception ex)
            {
                lbStatus.Text = @"Error";
                MessageBox.Show("Thong tin khong hop le vui long kiem tra lai\n\n" + ex.Message);
            }
            // }
            // else
            // {
            //    lbStatus.Text = @"Error";
            // }
        }

        private void BtnT2UpdateClick(object sender, EventArgs e)
        {
            try
            {
                string username = cbxT2UserName.Enabled ? cbxT2UserName.Text : txtT2UserName.Text;
                int x = usersTableAdapter.UpdateUser(
                    txtT2PassWord.Text,
                    txtT2FirstName.Text,
                    txtT2LastName.Text,
                    txtT2Address.Text,
                    txtT2State.Text,
                    txtT2City.Text,
                    txtT2Phone.Text,
                    txtT2Email.Text,
                    username
                    );
                if (x == 1)
                    lbStatus.Text = @"Update Successful";
            }
            catch (Exception ex)
            {
                lbStatus.Text = @"Error";
                MessageBox.Show(ex.Message);
            }
        }

        private void BtnT2DeleteClick(object sender, EventArgs e)
        {
            string username = cbxT2UserName.Enabled ? cbxT2UserName.Text : txtT2UserName.Text;
            try
            {
                int x = usersTableAdapter.DeleteUser(username);
                if (x == 1)
                {
                    lbStatus.Text = @"Delete Successful";
                    usersTableAdapter.Fill(newTech_BookStoreDataSet.Users);
                }
            }
            catch (Exception ex)
            {
                lbStatus.Text = @"Error";
                MessageBox.Show(ex.Message);
            }
        }

        //--------------tab 3

        private void ChbxT3ManualInsertCheckedChanged(object sender, EventArgs e)
        {
            if (chbxT3Select.Checked)
            {
                cbxT3BookID.Enabled = true;
                cbxT3UserName.Enabled = true;
                txtT3BookID.Enabled = false;
                txtT3UserName.Enabled = false;
            }
            else
            {
                cbxT3BookID.Enabled = false;
                cbxT3UserName.Enabled = false;
                txtT3BookID.Enabled = true;
                txtT3UserName.Enabled = true;
            }
        }

        private void BtnT3InsertBillClick(object sender, EventArgs e)
        {
            string bookid = (cbxT3BookID.Enabled ? cbxT3BookID.Text : txtT3BookID.Text);

            if (book1TableAdapter.FillByBookID(newTech_BookStoreDataSet.Book1, bookid) > 0)
            {
                DataTable dataTable = newTech_BookStoreDataSet.Tables["Book"];
                DataRow a = dataTable.Rows[0];
                string price = a[6].ToString();
                try
                {
                    var bill = new Bill
                                   {
                                       BookId = bookid,
                                       Rate = txtT3Rate.Text,
                                       Price = price
                                   };
                    _lstBill.Add(bill);
                    lstbxT3Book.Items.Add(bill.BookId);
                    grbxT3ListBook.Enabled = true;
                }
                catch (Exception ex)
                {
                    lbStatus.Text = @"Bill Uncorect";
                    MessageBox.Show(ex.Message);
                }
            }
            else
            {
                lbStatus.Text = @"Error BookId";
                MessageBox.Show(@"Uncorect BookId");
            }
        }

        private void BtnT3InsertPaymentClick(object sender, EventArgs e)
        {
            string username = cbxT3UserName.Enabled ? cbxT3UserName.Text : txtT3UserName.Text;

            if (users1TableAdapter.FillByUserName(newTech_BookStoreDataSet.Users1, username) > 0)
            {
                var payment = new Payment
                                  {
                                      UserName = username,
                                      CreditCardType = txtT3CreditCardType.Text,
                                      CreditCardNumber = txtT3CreditCardNumber.Text,
                                      PurchaseDate = DateTime.ParseExact(txtT3PurchaseDay.Text, "dd/MM/yyyy", null)
                                  };
                _payment = payment;


                grbxT3Payment.Enabled = false;
                grbxT3Bill.Enabled = true;
                btnT3FinalPayment.Enabled = true;
                btnT3NewPayment.Enabled = true;
            }
            else
            {
                lbStatus.Text = @"Error UserName";
                MessageBox.Show(@"Uncorect UserName");
            }
        }

        private void BtnT3RemoveBookClick(object sender, EventArgs e)
        {
            if (lstbxT3Book.SelectedIndex > -1)
            {
                _lstBill.RemoveAt(lstbxT3Book.SelectedIndex);
                lstbxT3Book.Items.Remove(lstbxT3Book.SelectedItem);
            }
        }

        private void LstbxT3BookSelectedIndexChanged(object sender, EventArgs e)
        {
            string bookid = lstbxT3Book.Text;
            cbxT3BookID.SelectedValue = bookid;
            grbxT4BookInfo.Visible = true;
        }

        private void BtnT3NewPaymentClick(object sender, EventArgs e)
        {
            _payment = new Payment();
            _lstBill = new List<Bill>();
            grbxT3Bill.Enabled = false;
            grbxT3Payment.Enabled = true;
            grbxT3ListBook.Enabled = false;
            //---------------------------
            txtT3UserName.Text = "";
            txtT3BookID.Text = "";
            txtT3CreditCardType.Text = "";
            txtT3CreditCardNumber.Text = "";
            txtT3Rate.Text = "";
            lstbxT3Book.Items.Clear();
        }

        private void BtnT3FinalPaymentClick(object sender, EventArgs e)
        {
            string str = InsertPaymentCreateBill();
            if (str == "Transaction Committed")
            {
                lbStatus.Text = str;
                grbxT3Bill.Enabled = false;
                btnT3FinalPayment.Enabled = false;
                btnT3NewPayment.Enabled = true;
            }
        }

        //---------------tab 4

        private void BtnT4EditBookClick(object sender, EventArgs e)
        {
            string bookid = txtT4BookID.Text;
            mainTab.SelectedIndex = 0;
            cbxT3BookID.Text = "";
            cbxT3BookID.SelectedValue = bookid;
        }

        private void BtnT4SearchClick(object sender, EventArgs e)
        {
            lsbxT4Resul.Items.Clear();
            List<Book> listBook = SearchBook(txtT4Fill.Text, radT4Title.Checked ? "Title" : "CategoryName");
            foreach (Book book in listBook)
            {
                lsbxT4Resul.Items.Add(book.Title);
            }
            _lstBook = listBook;
            txtT4Author.Text = "";
            txtT4BookID.Text = "";
            txtT4Category.Text = "";
            txtT4Description.Text = "";
            txtT4ISBN.Text = "";
            txtT4Price.Text = "";
            txtT4Publisher.Text = "";
            txtT4Title.Text = "";
        }

        private void LsbxT4ResulSelectedIndexChanged(object sender, EventArgs e)
        {
            Book book = _lstBook[lsbxT4Resul.SelectedIndex];
            txtT4Author.Text = book.Author;
            txtT4BookID.Text = book.BookId;
            txtT4Category.Text = book.Category;
            txtT4Description.Text = book.Description;
            txtT4ISBN.Text = book.Isbn;
            txtT4Publisher.Text = book.Publisher;
            txtT4Title.Text = book.Title;
            txtT4Price.Text = book.Price;
        }

        //---------------U

        private string InsertPaymentCreateBill()
        {
            string resul;
            const string sqlSelectPayment = "SELECT * FROM dbo.PaymentDetails";
            const string sqlSelectMaxPaymentId = "SELECT MAX(PaymentID) FROM dbo.PaymentDetails";
            const string sqlInsertPayment =
                "INSERT  dbo.PaymentDetails VALUES  (@PaymentID, @UserName,@CreditCardType, @CreditCardNumber, @TotalBillAmount, @PurchaseDate)";
            const string sqlUpdateTotalPaymentAmount =
                "UPDATE dbo.PaymentDetails SET TotalBillAmount=@TotalBillAmount WHERE PaymentID=@PaymentID";
            const string sqlSelectBill = "SELECT * FROM dbo.BillDetails";
            const string sqlSelectMaxBillNumber = "SELECT MAX(BillNumber) FROM dbo.BillDetails";
            const string sqlInsetBill = "INSERT  dbo.BillDetails VALUES  (@BillNumber, @BookID, @Rate, @PaymentID)";

            using (var connection = new SqlConnection(Settings.Default.NewTech_BookStoreConnectionString))
            {
                decimal totalBillAmount = 0;
                connection.Open();
                SqlTransaction transactions = connection.BeginTransaction();
                try
                {
                    using (var cmdSelectPaymentId = new SqlCommand(sqlSelectPayment, connection, transactions))
                    {
                        SqlDataReader raderPayment = cmdSelectPaymentId.ExecuteReader();
                        if (raderPayment.Read())
                        {
                            raderPayment.Close();
                            using (var cmdGetPaymentId = new SqlCommand(sqlSelectMaxPaymentId, connection, transactions)
                                )
                            {
                                using (SqlDataReader readerPaymentId = cmdGetPaymentId.ExecuteReader())
                                {
                                    readerPaymentId.Read();
                                    _payment.PaymentId = IdIndent(readerPaymentId.GetString(0));
                                }
                            }
                        }
                        else
                        {
                            raderPayment.Close();
                            _payment.PaymentId = "P0000";
                        }
                    }
                    using (var cmdInsertPayment = new SqlCommand(sqlInsertPayment, connection, transactions))
                    {
                        cmdInsertPayment.Parameters.AddWithValue("@PaymentID", _payment.PaymentId);
                        cmdInsertPayment.Parameters.AddWithValue("@UserName", _payment.UserName);
                        cmdInsertPayment.Parameters.AddWithValue("@CreditCardType", _payment.CreditCardType);
                        cmdInsertPayment.Parameters.AddWithValue("@CreditCardNumber", _payment.CreditCardNumber);
                        cmdInsertPayment.Parameters.AddWithValue("@TotalBillAmount", "0");
                        cmdInsertPayment.Parameters.AddWithValue("@PurchaseDate", _payment.PurchaseDate);
                        cmdInsertPayment.ExecuteNonQuery();
                    }
                    int flg = 0;

                    using (var cmdGetBillNumber = new SqlCommand(sqlSelectBill, connection, transactions))
                    {
                        using (SqlDataReader readerBill = cmdGetBillNumber.ExecuteReader())
                        {
                            if (readerBill.Read())
                                flg = 1;
                        }
                    }

                    foreach (Bill bill in _lstBill)
                    {
                        if (flg == 0)
                        {
                            bill.BillNumber = "B0000";
                            flg = 1;
                        }
                        else
                        {
                            using (
                                var cmdGetMaxBillNumber = new SqlCommand(sqlSelectMaxBillNumber, connection,
                                                                         transactions))
                            {
                                using (SqlDataReader readerBillNumber = cmdGetMaxBillNumber.ExecuteReader())
                                {
                                    readerBillNumber.Read();
                                    bill.BillNumber = IdIndent(readerBillNumber.GetString(0));
                                }
                            }
                        }

                        totalBillAmount = totalBillAmount + Convert.ToDecimal(bill.Price);
                        using (var cmdInsertBill = new SqlCommand(sqlInsetBill, connection, transactions))
                        {
                            cmdInsertBill.Parameters.AddWithValue("@BillNumber", bill.BillNumber);
                            cmdInsertBill.Parameters.AddWithValue("@BookID", bill.BookId);
                            cmdInsertBill.Parameters.AddWithValue("@Rate", bill.Rate);
                            cmdInsertBill.Parameters.AddWithValue("@PaymentID", _payment.PaymentId);
                            cmdInsertBill.ExecuteNonQuery();
                        }
                    }
                    using (
                        var cmdUpdateTotalPaymentAmount = new SqlCommand(sqlUpdateTotalPaymentAmount, connection,
                                                                         transactions))
                    {
                        cmdUpdateTotalPaymentAmount.Parameters.AddWithValue("@TotalBillAmount", totalBillAmount);
                        cmdUpdateTotalPaymentAmount.Parameters.AddWithValue("@PaymentID", _payment.PaymentId);
                        cmdUpdateTotalPaymentAmount.ExecuteNonQuery();
                    }
                    transactions.Commit();
                    lblT3PaymentID.Text = _payment.PaymentId;
                    lblT3TotalBillAmount.Text = totalBillAmount + @"$";
                    resul = "Transaction Committed";
                }
                catch (Exception ex)
                {
                    transactions.Rollback();
                    MessageBox.Show(string.Format("TRANSACTION ROLLED BACK\n{0}", ex.Message), @"Error",
                                    MessageBoxButtons.OK,
                                    MessageBoxIcon.Error);
                    resul = "TRANSACTION ROLLED BACK";
                }

                finally
                {
                    lsbxT4Resul.Items.Clear();
                    _lstBill = new List<Bill>();
                }
            }
            return resul;
        }

        private static string IdIndent(string id)
        {
            string a = id.Substring(0, 1);
            string b = Convert.ToString(Convert.ToInt32(id.Substring(1, id.Length - 1)) + 10001);
            string c = a + b.Substring(1, b.Length - 1);
            return c;
        }

        private List<Book> SearchBook(string key, string col)
        {
            bookTableAdapter.Fill(newTech_BookStoreDataSet.Book);
            DataTable dataTable = newTech_BookStoreDataSet.Tables["Book"];
            var dataView = new DataView(dataTable, string.Format("{0} like '%{1}%'", col, key), "Title",
                                        DataViewRowState.CurrentRows);
            List<Book> listBook = (from DataRowView drv in dataView
                                   select new Book
                                              {
                                                  BookId = drv[0].ToString(),
                                                  Title = drv[1].ToString(),
                                                  Category = drv[2].ToString(),
                                                  Author = drv[3].ToString(),
                                                  Publisher = drv[4].ToString(),
                                                  Isbn = drv[5].ToString(),
                                                  Price = drv[6].ToString(),
                                                  Description = drv[7].ToString()
                                              }).ToList();
            return listBook;
        }

        //-----

        public bool chkCusInfo()
        {
            string phone = txtT2Phone.Text;

            string strEmail = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
                  @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
                  @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(]?)$";
            string strPhone = @"\d{3}-\d{3}-\d{4}";

            Regex rePhone = new Regex(strPhone);
            Regex reEmail = new Regex(strEmail);

            if (rePhone.IsMatch(phone))
                return (true);
            else
                return (false);
        } 

        //----------------report

        // ReSharper disable MemberCanBeMadeStatic.Local
        private void BtnReportClick(object sender, EventArgs e)
        {
            var report = new Report();
            report.Show();
        }
    }
}